package demo;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

@RequestMapping(value = "/files")
@Controller
public class App {

    private static Logger logger = LoggerFactory.getLogger(App.class);

    private static File dir = null;

    @RequestMapping("/list")
    @ResponseBody
    Object list(HttpServletRequest request) throws IOException {
        String[] fileNames = dir.list();
        return fileNames;
    }

    @RequestMapping("/upload")
    @ResponseBody
    String upload(@RequestParam  MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws IOException {
        File destFile = new File(dir, file.getOriginalFilename());
        logger.info(file.getOriginalFilename() + "保存到" + destFile.getAbsolutePath());

        try (FileOutputStream out = new FileOutputStream(destFile)) {
            IOUtils.copy(file.getInputStream(), out);
        }

        response.sendRedirect("/index.html");
        return null;
    }

    public static void main(String[] args) throws Exception {
        String dirPath = args.length >= 1 ? args[0] : ".";
        dir = new File(dirPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        SpringApplication.run(new Object[]{AppConfig.class}, args);

        logger.info("文件所在目录=" + dir.getCanonicalPath());

    }

}



